const { saveAddress, addressList, deleteAddress, setDefault } = require('../../api/adderss')
const { API_OK } = require('../../utils/setting')
const app = getApp()

Page({
  data: {
    type: 'normal',
    loading: false,
    defaultAddressId: null,
    authSetting: {},
    addressList: [],
    xmove: []
  },
  pageData: {
    startX: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSetting()
    wx.showLoading({ title: '拼命加载中', mask: true })
    this.setData({ loading: true, type: options.type || 'normal' })
    if (wx.getStorageSync('token')){
      this.getAddressList()
    } else {
      app.tokenReadyCallback = this.getAddressList
      app.getTokenFailedCallback = () => {
        wx.hideLoading()
        this.setData({ loading: false })
      }
    }
  },
  /**
   * 检查是否获取地址权限
   */
  getSetting() {
    wx.getSetting({
      success: (result)=>{
        // console.log(result)
        this.setData({ authSetting: result.authSetting })
      }
    })
  },
  /**
   * 导入地址
   */
  importAddress() {
    wx.chooseAddress({
      success: async (result)=>{
        // console.log(result)
        if (result.errMsg === 'chooseAddress:ok') {
          this.addAddress(result)
        } else {
          this.getSetting()
        }
      },
      fail: (err)=>{
        console.warn('choose address fail: ', err)
        this.getSetting()
      }
    })
  },
  /**
   * 添加地址
   */
  async addAddress(address) {
    try {
      wx.showLoading({ title: '正在添加地址', mask: true })
      const res = await saveAddress({
        header: { 'Content-Type':'application/x-www-form-urlencoded' },
        data: {
          name: address.userName,
          phone: address.telNumber,
          region: [address.provinceName, address.cityName, address.countyName],
          detail: address.detailInfo
        },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === 200) {
        wx.showToast({ title: '地址添加成功', icon: 'success', duration: 1500 })
        setTimeout(() => {
          wx.showLoading({ title: '拼命加载中', mask: true })
          this.getAddressList()
        }, 1500)
      } else {
        wx.showToast({ title: '添加地址失败', icon: 'none', mask: true, duration: 1500 })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 删除地址
   */
  deleteAddress(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除此地址么',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async (result) => {
        if(result.confirm){
          const addressId = this.data.addressList[e.currentTarget.dataset.index].address_id
          try {
            wx.showLoading({ title: '正在删除地址', mask: true })
            const res = await deleteAddress({
              data: { address_id: addressId },
              callback: wx.hideLoading
            })
            console.log(res)
            if (res.code === 200) {
              wx.showToast({ title: '地址删除成功', duration: 1500, mask: true })
              this.data.addressList.splice(e.currentTarget.dataset.index, 1)
              this.data.xmove.splice(e.currentTarget.dataset.index, 1)
              this.setData({ addressList: this.data.addressList, xmove: this.data.xmove })
            } else {
              wx.showToast({ title: '地址删除失败', icon: 'none', duration: 1500, mask: true })
            }
          } catch(err) {
            console.warn(err)
          }
        }
      }
    })
  },
  /**
   * 打开授权
   */
  openSetting() {
    wx.openSetting({
      success: (result)=>{
        // console.log(result)
        this.setData({ authSetting: result.authSetting })
      },
      fail: (err)=>{
        console.warn(err)
      },
      complete: ()=>{}
    });
  },
  showDeleteButton(e) {
    const index = e.currentTarget.dataset.index
    this.setXmove(index, -65)
  },
  hideDeleteButton(e) {
    const index = e.currentTarget.dataset.index
    this.setXmove(index, 0)
  },
  setXmove(index, xmove) {
    // const addressList = JSON.parse(JSON.stringify(this.data.addressList))
    // addressList[index].xmove = xmove
    // this.setData({ addressList })
    this.data.xmove[index].xmove = xmove
    this.setData({ xmove: this.data.xmove })
  },
  handleMovableChange(e) {
    if (e.detail.source === 'friction') {
      if (e.detail.x < -30) {
        this.showDeleteButton(e)
      } else {
        this.hideDeleteButton(e)
      }
    } else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
      this.hideDeleteButton(e)
    }
  },
  handleTouchstart(e) {
    this.pageData.startX = e.touches[0].pageX
  },
  handleTouchend(e) {
    if (Math.abs(e.changedTouches[0].pageX - this.pageData.startX) < 1 || !this.pageData.startX) {
      this.pageData.startX = 0
      return
    }
    if (e.changedTouches[0].pageX < this.pageData.startX && e.changedTouches[0].pageX - this.pageData.startX <= -30) {
      this.showDeleteButton(e)
    } else if (e.changedTouches[0].pageX > this.pageData.startX && e.changedTouches[0].pageX - this.pageData.startX < 30) {
      // this.showDeleteButton(e)
    } else {
      this.hideDeleteButton(e)
    }
    this.pageData.startX = 0
  },
  /**
   * 获取地址列表
   */
  async getAddressList() {
    try {
      const res = await addressList({
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          loading: false,
          addressList: res.data.list,
          defaultAddressId: res.data.default_id,
          xmove: res.data.list.map(item => ({ id: item.address_id, xmove: 0 }))
        })
      }
    } catch(err) {
      console.warn(err)
      this.setData({ loading: false })
    }
  },
  /**
   * 选择地址
   */
  chooseAddress({ currentTarget }) {
    console.log(currentTarget.dataset.index)
    let pages =  getCurrentPages()
    if (pages[pages.length - 2]) {
      pages[pages.length - 2].chooseAddressCallback = () => this.data.addressList[currentTarget.dataset.index]
      this.data.type === 'chooseAddress' && wx.navigateBack({ delta: 1 })
    }
  },
  /**
   * 设置为默认地址
   */
  async setDefault(e) {
    wx.showLoading({ title: '正在设置', mask: true, })
    try {
      const res = await setDefault({
        data: { address_id: e.currentTarget.dataset.id },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        wx.showToast({ title: '设置成功', icon: 'success', duration: 1500, mask: false })
        this.getAddressList()
      }
    } catch(err) {
      console.warn(err)
    }
  }
})
